﻿
using Edu.Application.Interfaces;
using Edu.Application.Model.RequestModel;
using Edu.Domain;
using Edu.Domain.Model;
using EStart.DataBase.EF;
using EStart.DataBase.Event.Domian;
using EStart.Infrastructure.ClientData;
using QuestionBank.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Edu.Application.Model.Messaging;
using Edu.Application.Model.ResponseModel;
using EStart.Infrastructure.Domain;
using Microsoft.EntityFrameworkCore;
using EStart.Infrastructure.Extensions;
using Edu.Application.Extensions;
using Edu.Application.Model.Models;

namespace Edu.Application.Implements
{
    public class RoleService : ServiceCore<Role>, IRoleService
    {
        private readonly IUserMenuOrActionInRoleService _userMenuOrActionInRoleService;

        public RoleService(
            EduDbContext context,
            EventDbContext eventDbContext,
            IUserMenuOrActionInRoleService userMenuOrActionInRoleService
            ) : base(context, eventDbContext)
        {
            _userMenuOrActionInRoleService = userMenuOrActionInRoleService;
        }

        public async Task<ApiResult<List<CheckModel>>> GetCheckModelAsync()
        {
            ApiResult<List<CheckModel>> response = new ApiResult<List<CheckModel>>();
            try
            {

                var check = await Query().Select(n => new CheckModel
                {
                    label = n.Name,
                    value = n.ID
                }).ToListAsync();
                response.success = true;
                response.data = check;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }
        public ApiResult<string> Delete(Guid guid)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {

                var school = Query().Where(n => n.Guid == guid).FirstOrDefault();
                if (school == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                DeleteForge(school);
                var b = _unitofwork.Commit();
                response.success = b;
                response.message = b ? "删除成功！" : "删除失败！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "删除失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public ApiResult<RoleModel> GetDetail(Guid guid)
        {
            ApiResult<RoleModel> response = new ApiResult<RoleModel>();
            try
            {

                var entity = Query().Where(n => n.Guid == guid)
                    .Select(n => new RoleModel
                    {
                        CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        guid = n.Guid.ToString(),
                        Name = n.Name,
                        Remark = n.Remark,
                        Menu = n.RoleAndMenu.Select(c => c.UserMenuID).ToList()
                    }).FirstOrDefault();
                if (entity == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                response.success = true;
                response.data = entity;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public async Task<ApiResult<Page<RoleModel>>> GetPagesAsync(RolePage request)
        {
            ApiResult<Page<RoleModel>> response = new ApiResult<Page<RoleModel>>();
            try
            {
                var pages = await Query()
                            .HasWhere(request.RoleName, n => n.Name.Contains(request.RoleName))
                            .Select(n => new RoleModel
                            {
                                CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                guid = n.Guid.ToString(),
                                Name = n.Name,
                                Remark = n.Remark
                            }).OrderByDescending(n => n.CreateTime).ToPageAsync(request.PageIndex, request.PageSize);

                response.success = true;
                response.message = "获取成功！";
                response.data = pages;
                return response;

            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误：" + ex.Message;
                return response;
            }
        }



        public async Task<ApiResult<string>> SaveAsync(RoleModel request)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {
                if (string.IsNullOrEmpty(request.guid))
                {

                    Role model = new Role();
                    model.Remark = request.Remark;
                    model.Name = request.Name;
                    await _unitofwork.RegisterNewAsync(model);
                }
                else
                {
                    var sguid = Guid.Parse(request.guid);
                    var old = Query().Where(n => n.Guid == sguid).FirstOrDefault();
                    if (old == null)
                    {
                        throw new Exception("未找到修改数据！！");
                    }

                    old.Name = request.Name;
                    old.Remark = request.Remark;

                    _unitofwork.RegisterDirty(old);

                }

                var b = await _unitofwork.CommitAsync();

                response.success = b;
                response.message = b ? "保存成功！" : "保存失败";
                return response;
            }
            catch (Exception ex)
            {

                response.message = "发生错误：" + ex.Message;
                return response;
            }
        }

        public async Task<ApiResult<string>> SaveUseMenuAsync(UserMenuAndUserActionRequest request)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {
                var roleguid = Guid.Parse(request.guid);
                var role = await Query().Where(n => n.Guid == roleguid).FirstOrDefaultAsync();
                if (role == null)
                {
                    throw new Exception("未找到角色数据！！");
                }
                var raaList = await _userMenuOrActionInRoleService.Query().Where(n => n.RoleID == role.ID).ToListAsync();
                var MenuID = request.MenuAndActionList.Where(n => n.Split('-').Length == 3).ToList();
                foreach (var item in MenuID)
                {
                    UserMenuOrActionInRole uarole = new UserMenuOrActionInRole();
                    var itemlist = item.Split('-');
                    if (itemlist.Length == 3)
                    {
                        //判断有没有

                        uarole.FatherMenuID = int.Parse(itemlist[0]);
                        uarole.UserMenuID = int.Parse(itemlist[1]);
                        uarole.UserActionID = int.Parse(itemlist[2]);
                        uarole.RoleID = role.ID;
                        var raa = raaList
                            .Where(n => n.FatherMenuID == uarole.FatherMenuID)
                            .Where(n => n.UserMenuID == uarole.UserMenuID)
                            .Where(n => n.UserActionID == uarole.UserActionID)
                            .FirstOrDefault();
                        if (raa == null)
                        {
                            await _unitofwork.RegisterNewAsync(uarole);
                        }
                    }
                }
                //删除数据库有的，而保存的没有的
                foreach (var item in raaList)
                {
                    var faString = item.FatherMenuID + "-" + item.UserMenuID + "-" + item.UserActionID;
                    var haveCount = MenuID.Where(n => n == faString).Count();
                    if (haveCount == 0)
                    {
                        _unitofwork.RegisterDeleted(item);
                    }
                }
                var b = await _unitofwork.CommitAsync();
                response.success = b;
                response.message = b ? "保存成功！" : "保存失败";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "发生错误：" + ex.Message;
                return response;

            }
        }

        public async Task<ApiResult<List<string>>> GetCheckByRoleGuid(Guid guid)
        {
            ApiResult<List<string>> response = new ApiResult<List<string>>();
            try
            {
                var role = await Query().Where(n => n.Guid == guid).FirstOrDefaultAsync();
                if (role == null)
                {
                    throw new Exception("未找到角色数据！！");
                }

                var idlist = await _userMenuOrActionInRoleService.Query().Where(n => n.RoleID == role.ID).Select(n => new
                {
                    n.FatherMenuID,
                    n.UserMenuID,
                    n.UserActionID
                }).ToListAsync();
                List<string> ls = new List<string>();
                foreach (var item in idlist)
                {
                    var lsstring = item.FatherMenuID + "-" + item.UserMenuID + "-" + item.UserActionID;
                    ls.Add(lsstring);
                }
                response.success = true;
                response.message = "获取成功！";
                response.data = ls;
                return response;
            }
            catch (Exception ex)
            {
                response.message = "发生错误：" + ex.Message;
                return response;
            }
        }
    }
}
